﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Text.RegularExpressions;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;

namespace RMBoink
{
    public static class ClassVars
    {
        public static int LastTimeStamp;

        public static bool AmbigContains(this string source, string toCheck, StringComparison comp)
        {
            return source.IndexOf(toCheck, comp) >= 0;
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private FrameworkElement _title;

        public static double ConvertSecondsToMilliseconds(double seconds)
        {
            return TimeSpan.FromSeconds(seconds).TotalMilliseconds;
        }

        public MainWindow()
        {
            InitializeComponent();
            /* if (Debugger.IsAttached)
                Settings.Default.Reset(); */
            if ((bool)Properties.Settings.Default["IsFirstRun"] == true)
            {
                Welcome welcomepage = new Welcome();
                welcomepage.Show();
                App.Current.MainWindow = welcomepage;
                this.Close();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ///DEBUG SOUND
            if (Properties.Settings.Default["Sound"].ToString() != null && Properties.Settings.Default["Sound"].ToString() != "")
            {
                if (Properties.Settings.Default["Sound"].ToString().AmbigContains("mp3", StringComparison.OrdinalIgnoreCase))
                {
                    var reader = new NAudio.Wave.Mp3FileReader(Properties.Settings.Default["Sound"].ToString());
                    var waveOut = new NAudio.Wave.WaveOut(); // or WaveOutEvent()
                    waveOut.Init(reader);
                    waveOut.Play();
                }
                else if (Properties.Settings.Default["Sound"].ToString().AmbigContains("wav", StringComparison.OrdinalIgnoreCase))
                {
                    SoundPlayer player = new SoundPlayer(Properties.Settings.Default["Sound"].ToString());
                    var sound = Properties.Settings.Default["Sound"].ToString();
                    SoundFile.Text = Properties.Settings.Default["Sound"].ToString();
                    player.Load();
                    player.Play();
                }
            }
            else
            {
                Stream str = Properties.Resources.ding;
                SoundPlayer snd = new SoundPlayer(str);
                snd.Play();
            }
            ///END DEBUG SOUND
            this._title = (FrameworkElement)this.Template.FindName("PART_Title", this);
            if (null != this._title)
            {
                this._title.MouseLeftButtonDown += new MouseButtonEventHandler(title_MouseLeftButtonDown);
            }
            RegionBox.Text = Properties.Settings.Default["Region"].ToString();
            UpdateTime.Text = Properties.Settings.Default["UpdateTime"].ToString();
            NationsIgnore.Text = Properties.Settings.Default["Ignored"].ToString();
            var regionname = Properties.Settings.Default["Region"].ToString();
            var interval = Properties.Settings.Default["UpdateTime"].ToString();
            var ignorednations = Properties.Settings.Default["Ignored"].ToString();
            if (RegionBox.Text != "")
            {
                if (Int32.Parse(interval) < 1)
                {
                    System.Windows.MessageBox.Show("Your interval is invalid. Please try again.");
                    Properties.Settings.Default["UpdateTime"] = 1;
                    Properties.Settings.Default.Save(); // Saves settings in application configuration file
                    System.Windows.Forms.Application.Restart();
                    System.Windows.Application.Current.Shutdown();
                }
                var intervalmillisecs = ConvertSecondsToMilliseconds(Convert.ToDouble(interval));
                try
                {
                    String URLString = "https://www.nationstates.net/cgi-bin/api.cgi?region=" + regionname + "&q=messages&v=7";
                    WebRequest request = WebRequest.Create(URLString);
                    ((HttpWebRequest)request).UserAgent = "RMBoink Client Application created by Namayapata";
                    WebResponse response = request.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    XDocument doc = XDocument.Load(responseStream);
                    XElement root = doc.Root;
                    ClassVars.LastTimeStamp = (int)root.Descendants("TIMESTAMP").Last();
                }
                catch (WebException)
                {
                    System.Windows.MessageBox.Show("Error connecton to NationStates. Please press OK to see the NationStates website and check the error there.");
                    Process.Start("https://www.nationstates.net/cgi-bin/api.cgi");
                    System.Windows.Application.Current.Shutdown();
                }
                catch
                {
                    System.Windows.MessageBox.Show("Your region name is invalid. Please try again.");
                    Properties.Settings.Default["Region"] = "";
                    Properties.Settings.Default.Save(); // Saves settings in application configuration file
                    System.Windows.Forms.Application.Restart();
                    System.Windows.Application.Current.Shutdown();
                }
                System.Timers.Timer aTimer = new System.Timers.Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                aTimer.Interval = intervalmillisecs;
                aTimer.Enabled = true;
                aTimer.Start();
            }
        }

        private string RemoveHtmlTags(string html)
        {
            return Regex.Replace(html, "[.+?]", string.Empty);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            var regionname = Properties.Settings.Default["Region"].ToString();
            String URLString = "https://www.nationstates.net/cgi-bin/api.cgi?region=" + regionname + "&q=messages&v=7";
            WebRequest request = WebRequest.Create(URLString);
            ((HttpWebRequest)request).UserAgent = "RMBoink Client Application created by Namayapata";
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            XDocument doc = XDocument.Load(responseStream);
            XElement root = doc.Root;
            if ((int)root.Descendants("TIMESTAMP").Last() > ClassVars.LastTimeStamp && Properties.Settings.Default["Ignored"].ToString().AmbigContains((string)root.Descendants("NATION").Last(), StringComparison.OrdinalIgnoreCase) == false)
            {
                if (Properties.Settings.Default["Sound"].ToString() != null && Properties.Settings.Default["Sound"].ToString() != "")
                {
                    if (Properties.Settings.Default["Sound"].ToString().AmbigContains("mp3", StringComparison.OrdinalIgnoreCase))
                    {
                        var reader = new NAudio.Wave.Mp3FileReader(Properties.Settings.Default["Sound"].ToString());
                        var waveOut = new NAudio.Wave.WaveOut(); // or WaveOutEvent()
                        waveOut.Init(reader);
                        waveOut.Play();
                    }
                    else if (Properties.Settings.Default["Sound"].ToString().AmbigContains("wav", StringComparison.OrdinalIgnoreCase))
                    {
                        SoundPlayer player = new SoundPlayer(Properties.Settings.Default["Sound"].ToString());
                        var sound = Properties.Settings.Default["Sound"].ToString();
                        SoundFile.Text = Properties.Settings.Default["Sound"].ToString();
                        player.Load();
                        player.Play();
                    }
                }
                else
                {
                    Stream str = Properties.Resources.ding;
                    SoundPlayer snd = new SoundPlayer(str);
                    snd.Play();
                }
                string title = "New RMB message";
                string text = RemoveHtmlTags((string)root.Descendants("MESSAGE").Last());

                //show balloon with custom icon
                TBIcon.ShowBalloonTip(title, text, TBIcon.Icon);
            }
            ClassVars.LastTimeStamp = (int)root.Descendants("TIMESTAMP").Last();
        }

        private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void Settings_Click(object sender, RoutedEventArgs e)
        {
            Show();
        }

        private void Quit_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }

        private void TBIcon_TrayContextMenuOpen(object sender, System.EventArgs e)
        {
        }

        private void TBIcon_PreviewTrayContextMenuOpen(object sender, System.EventArgs e)
        {
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            //clean up notifyicon (would otherwise stay open until application finishes)
            TBIcon.Dispose();
            base.OnClosing(e);
            if (Properties.Settings.Default["IsFirstRun"].Equals(false))
            {
                System.Windows.Application.Current.Shutdown();
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Hide();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var updatefloat = float.Parse(UpdateTime.Text);
            Properties.Settings.Default["Region"] = RegionBox.Text;
            Properties.Settings.Default["UpdateTime"] = updatefloat;
            if (SoundFile.Text != "custom sound file (optional)" && SoundFile.Text != null && SoundFile.Text != "")
            {
                Properties.Settings.Default["Sound"] = SoundFile.Text;
            }
            Properties.Settings.Default["Ignored"] = NationsIgnore.Text.Replace(" ", "_");
            Properties.Settings.Default.Save(); // Saves settings in application configuration file
            System.Windows.Forms.Application.Restart();
            System.Windows.Application.Current.Shutdown();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        private void Browse_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".mp3";
            dlg.Filter = "Windows Audio Files (*.wav)|*.wav|MPEG Audio Files (*.mp3)|*.mp3";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                SoundFile.Text = filename;
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Process.Start("http://rmboink.userecho.com/");
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
                Hide();
        }

        private void HideButton_Click(object sender, RoutedEventArgs e)
        {
            Hide();
        }
    }
}